import http from '@/utils/http'
import { getLocalChannels, hasToken, setLocalChannels } from '@/utils/storage'
import store, { AppDispatch } from '..'
import { Channel } from '../reducer/channel'

/**
 * 获取用户频道列表
 * @returns {Promise} Promise<void>
 */
export const getUserChannels = () => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      // 情况1：如果用户登录了，发送请求获取该用户的频道信息
      const res = await http.get(`/v1_0/user/channels`)
      console.log(`情况1：返回用户关注的频道`, res)
      // 存储到 redux 用于界面渲染
      dispatch({ type: 'channel/saveList', payload: res.data.channels })
    } else {
      // 情况2：用户未登录情况，也可以关注自己喜欢的频道（本地存储）
      const localList = getLocalChannels()
      if (localList.length) {
        //  情况2.1: 本地有频道数据，存储到 redux 中用于界面渲染
        dispatch({ type: 'channel/saveList', payload: localList })
      } else {
        //  情况2.2: 本地没有频道数据，发送请求，获取默认频道列表，存储到 redux 中用于界面渲染
        const res = await http.get(`/v1_0/user/channels`)
        console.log(`情况2：返回默认频道`, res)
        // 存储到 redux 用于界面渲染
        dispatch({ type: 'channel/saveList', payload: res.data.channels })
        // 未登录情况：本地存储保存一份频道信息
        setLocalChannels(res.data.channels)
      }
    }
  }
}

/**
 * 获取所有频道列表
 * @returns {Promise} Promise<void>
 */
export const getAllChannels = () => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get(`/v1_0/channels`)
    // console.log(`/v1_0/channels`, res)
    dispatch({ type: 'channel/saveAllList', payload: res.data.channels })
  }
}

/**
 * 添加用户频道
 * @param item Channel
 * @returns
 */
export const addChannel = (item: Channel) => {
  return async (dispatch: AppDispatch) => {
    const { list } = store.getState().channel
    // 添加频道到列表末尾
    const channels = [...list, item]
    if (hasToken()) {
      // 情况1：发送请求
      const res = await http.patch(`/v1_0/user/channels`, { channels: channels })
      console.log(res)
    } else {
      // 情况2：用户未登录，把数据存到本地存储
      setLocalChannels(channels)
    }

    dispatch({ type: 'channel/saveList', payload: channels })
  }
}

/**
 * 删除指定用户频道
 * @param item
 * @returns
 */
export const deleteChannel = (id: number) => {
  return async (dispatch: AppDispatch) => {
    // 获取仓库的用户频道列表
    const { list } = store.getState().channel
    const newList = list.filter((v) => v.id !== id)
    if (hasToken()) {
      // 情况1：已登录，发送请求
      const res = await http.delete(`/v1_0/user/channels/${id}`)
      console.log(`/v1_0/user/channels/${id}`, res)
    } else {
      // 情况2：未登录，修改本地存储
      setLocalChannels(newList)
    }
    // 更新 redux 数据，用于更新 UI 界面
    dispatch({ type: 'channel/saveList', payload: newList })
  }
}

/**
 * 更新选中频道id
 * @param item
 * @returns
 */
export const changeChannelId = (id: number) => {
  return async (dispatch: AppDispatch) => {
    dispatch({ type: 'channel/changeActiveId', payload: id })
  }
}
